/*
 * @Author: Langxiaobai 3369824473@qq.com
 * @Date: 2025-05-15 01:28:15
 * @LastEditors: Langxiaobai 3369824473@qq.com
 * @LastEditTime: 2025-06-21 14:46:54
 * @FilePath: \rwm\app\market\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
  Text,
  StyleSheet,
  View,
  Image,
  TouchableOpacity,
  ScrollView,
} from "react-native";
import React, { useState } from "react";
import PageContainer from "@/components/PageContainer";
import useAppStateChange from "@/hooks/useAppStateChange";
import { useRouter } from "expo-router";
import { useTranslation } from "react-i18next";
import { ToastAPI } from "@/components/Toast";
import { get, post } from "@/uitls/axios";

const queryLatestMarketConditionFnAPi = () => {
  return new Promise((resolve, reject) => {
    get("/apis/market/searchMarketCondition")
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

export default function Market() {
  const appState = useAppStateChange();
  const router = useRouter();
  const [selectedButton, setSelectedButton] = useState(0);
  const { t } = useTranslation();
  const [currencyData, setCurrencyData] = useState<any[]>([]);
  const getLatestMarketCondition = async () => {
    ToastAPI.loading(t("common.loading"), "center", -1);
    try {
      const queryLatestMarketConditionFnAPiRes: any =
        await queryLatestMarketConditionFnAPi();
      ToastAPI.close();
      if (queryLatestMarketConditionFnAPiRes.code === 0) {
        setCurrencyData(queryLatestMarketConditionFnAPiRes?.result || []);
      } else {
        ToastAPI.error(
          queryLatestMarketConditionFnAPiRes?.errMsg || t("common.loadFailed")
        );
      }
    } catch (error) {
      ToastAPI.close();
      // 捕获错误并关闭加载提示
      ToastAPI.error(JSON.stringify(error) || t("common.loadFailed"));
    }
  };
  React.useEffect(() => {
    getLatestMarketCondition();
  }, []);

  const handleButtonPress = (index: number) => {
    setSelectedButton(index);
    index === 0 ? getLatestMarketCondition() : setCurrencyData([]);
  };

  return (
    <PageContainer>
      <View className="bg-[#000] flex-1 p-[13px]">
        <View className="items-center flex-row h-[46px]">
          <TouchableOpacity onPress={() => router.back()}>
            <Image
              source={require("@/assets/images/return-left.png")}
              className="w-[18px] h-[18px]"
            />
          </TouchableOpacity>
          <View className="flex-1 flex-row justify-center">
            <View className="flex-row items-center">
              <TouchableOpacity onPress={() => handleButtonPress(0)}>
                <Text
                  style={{
                    borderTopLeftRadius: 8,
                    borderBottomLeftRadius: 8,
                    backgroundColor:
                      selectedButton === 0 ? "#478CFE" : "#3D3D3D",
                  }}
                  className="text-[#fff] text-[16px] w-[72px] text-center h-[40px] leading-[40px]"
                >
                  {t("marketx.market")}
                </Text>
              </TouchableOpacity>
              <TouchableOpacity onPress={() => handleButtonPress(1)}>
                <Text
                  style={{
                    borderTopRightRadius: 8,
                    borderBottomRightRadius: 8,
                    backgroundColor:
                      selectedButton === 1 ? "#478CFE" : "#3D3D3D",
                  }}
                  className="text-[#fff] text-[16px] w-[72px] text-center  h-[40px] leading-[40px]"
                >
                  {t("marketx.selected")}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
          {/* <Image
            source={require("@/assets/images/search.png")}
            className="w-[18px] h-[18px]"
          /> */}
          <View className="w-[18px] h-[18px]"></View>
        </View>
        {currencyData.length > 0 ? (
          <ScrollView
            showsVerticalScrollIndicator={false}
            showsHorizontalScrollIndicator={false}
            style={{ flex: 1 }}
          >
            <View>
              <View className="mt-[22px]">
                <View className="justify-between items-center flex-row">
                  <View className="gap-[10px] items-center flex-row">
                    <Image
                      source={require("@/assets/images/rectangle.png")}
                      className="w-[3px] h-[18px]"
                    ></Image>
                    <Text className="text-[#fff] text-[18px] font-[bold]">
                      {t("marketx.hot_data")}
                    </Text>
                  </View>
                </View>
              </View>
              <View className="mt-[22px] flex-row">
                <View className="flex-1">
                  <Text className="text-[14px] text-[#949494]">
                    {t("marketx.currency")}
                  </Text>
                </View>
                <View className="flex-row gap-[35px] items-center ">
                  <View className="w-[84px]">
                    <Text className="text-[14px] text-[#949494] w-[84px] text-right">
                      {t("marketx.price")}
                    </Text>
                  </View>
                  <Text className="text-[14px] text-[#949494]  w-[84px]  text-right">
                    {t("marketx.change_rate")}
                  </Text>
                </View>
              </View>
              {currencyData.map((item, index) => (
                <TouchableOpacity
                  key={index}
                  onPress={() => {
                    router.push({
                      pathname: "/market/marketdw",
                      params: {
                        tradingSymbol: item?.tradingSymbol,
                        tradingId: item?.tradingId,
                        secondaryAssetSymbol: item?.secondaryAssetSymbol,
                        mainAssetSymbol: item?.mainAssetSymbol,
                        price: item?.price,
                        changeRatio: item?.changeRatio,
                      },
                    });
                  }}
                >
                  <View className="mt-[13px] flex-row items-center mb-[25px]">
                    <View className="flex-1  flex-row gap-[5px]">
                      <Image
                        source={{
                          uri:
                            item?.logo ||
                            "https://t10.baidu.com/it/u=1563580236,1863594247&fm=199&app=68&f=JPEG?w=750&h=1000&s=43A23C6243C576E15FF911C60000E0A3",
                        }}
                        className="w-[25px] h-[25px] rounded-full"
                      ></Image>
                      <View className="flex-row gap-[5px] items-center">
                        <Text className="text-[#fff] text-[16px]">
                          {item?.mainAssetSymbol || "-"}
                        </Text>
                        <Text className="text-[#fff] text-[16px]">/</Text>
                        <Text className="text-[#9C9C9E] text-[16px]">
                          {item?.secondaryAssetSymbol || "-"}
                        </Text>
                      </View>
                    </View>
                    <View className="flex-row gap-[35px] items-center ">
                      <View className="w-[84px]">
                        {/* <Text className="text-[16px] text-[#fff] text-right">
                          3.0487
                        </Text> */}
                        <Text className="text-[14px] text-[#9C9C9E] text-right">
                          ¥{item?.price || "-"}
                        </Text>
                      </View>
                      <Text
                        className="w-[84px] text-center rounded-[5px] h-[35px] leading-[35px]"
                        style={{
                          backgroundColor:
                            item.changeRatio && parseFloat(item.changeRatio) < 0
                              ? "#EA4474"
                              : "#0BBB73",
                          color: "#fff",
                        }}
                      >
                        {parseFloat(item.changeRatio) < 0 ? "" : "+"}
                        {item?.changeRatio}%
                      </Text>
                    </View>
                  </View>
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>
        ) : (
          <View className="justify-center items-center" style={{ flex: 1 }}>
            <Image
              source={require("@/assets/images/empty.png")}
              className="w-[143px] h-[100px]"
            />
            <Text className="text-[#fff] text-[14px] mt-[10px]">
              {t("marketx.no_data")}
            </Text>
          </View>
        )}
      </View>
    </PageContainer>
  );
}

const styles = StyleSheet.create({});
